//
//  MyConcernFileViewController.m
//  homeland
//
//  Created by SunShine on 13-10-20.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "MyConcernFileViewController.h"
#import "MKNetworkKit.h"

@interface MyConcernFileViewController ()

@end

@implementation MyConcernFileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"详情";
    [self loadFile];
}

-(void)loadFile
{
    NSString *fileUrl = [_config objectForKey:@"fileUrl"];
    NSString *hostName;
    if (!fileUrl || fileUrl == (id)[NSNull null]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"传入的文件地址异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if ([fileUrl hasPrefix:@"http://"]) {
        hostName = [fileUrl substringFromIndex:7];
    } else if ([fileUrl hasPrefix:@"https://"]) {
        hostName = [fileUrl substringFromIndex:8];
    } else {
        hostName = fileUrl;
    }
    //write to file
    NSFileManager *theFileManager = [NSFileManager defaultManager];
    NSURL *theCacheURL = [[theFileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *url = [theCacheURL URLByAppendingPathComponent:[hostName lastPathComponent]];
    NSLog(@"拼装的缓存文件路径为%@",url);
    [self startLoadingView];
    _loadingView.mode = MBProgressHUDModeAnnularDeterminate;
    __weak MBProgressHUD *weakProgressView = _loadingView;
    __weak NSURL *weakURL = url;
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:hostName customHeaderFields:nil];
    MKNetworkOperation *op = [engine operationWithPath:nil params:nil httpMethod:@"GET"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSData *data = [completedOperation responseData];
        [data writeToURL:weakURL atomically:YES];
        [self stopLoadingView];
        [self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:weakURL];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        [self stopLoadingView];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"网络错误，加载文件失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
    [op onDownloadProgressChanged:^(double progress) {
        NSLog(@"文件下载进度%f", progress);
        weakProgressView.progress = progress;
    }];
    [engine enqueueOperation:op];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
